package work.chenbo.mybatis.customize.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import work.chenbo.mybatis.customize.io.Resources;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author ChenBo
 * @className XmlConfiguratonBulider
 * @date 2020/12/23
 */
public class XmlConfigurationBuilder {

    private Configuration configuration;


    public XmlConfigurationBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        List<Element> elements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : elements){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        DruidDataSource druidDataSource = new DruidDataSource();
//        druidDataSource.setDriverClassName(properties.getProperty("driverClass"));
//        druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
//        druidDataSource.setUsername(properties.getProperty("username"));
//        druidDataSource.setPassword(properties.getProperty("password"));

        druidDataSource.setUrl("jdbc:mysql://47.98.38.211:14569/lago");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //这个可以缺省的，会根据url自动识别
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");

        druidDataSource.setInitialSize(10);
        druidDataSource.setMaxActive(30);
        druidDataSource.setMinIdle(10);
        druidDataSource.setMaxWait(2000);
        druidDataSource.setPoolPreparedStatements(true);
        druidDataSource.setMaxOpenPreparedStatements(20);

        configuration.setDataSource(druidDataSource);




        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
        for (Element element: mapperElements){
            String mapperPath = element.attributeValue("resources");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parseMapper(resourceAsStream);
        }
        return configuration;

    }
}
